<script lang="ts" setup>
import { ref, watchEffect, reactive } from 'vue';
import { request } from "@/service/request";
import { requestToast } from "@/utils/requestToast";
import PhoneLogin from './plugin/PhoneLogin.vue';
import { mStyles } from "@/utils/useStyles";
import { useFullPage } from "@/hook/useFullPage";
import API from "@/service/api/login";
import order from "@/service/api/order";
import PasswordField from './plugin/password.vue'
import { someFieldStore } from '@/stores/somefield';
import { getUrlParamValue } from "@/utils/getUrlParams";
import { useRouter } from 'vue-router';
import { useStore } from "@/stores/user"

//是否客户端
const mSomeField = someFieldStore();  //客户端传的参数

//用户信息
const mUser = useStore();

const mPhoneLoginParams = reactive({
    phone: "",
    sms_code: "",
});

const mChangePasswordParams = reactive({
    password: "",
    confirm_password: "",
});


//获取用户绑定手机号
const mBingPhone = ref('');
const clkUserPhone = async () => {
    const { data } = await request.post<any>(order.userInfo);
    // 手机号脱敏处理
    if (data.telephone && data.telephone.length === 11) {
        mBingPhone.value = data.telephone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
    } else {
        mBingPhone.value = data.telephone || '';
    }
};
clkUserPhone()

// 接收手机号组件校验状态
const mNextStep = ref(true);  //提交按钮禁用状态
const mCheckCode = ref(false);
const mChangePassword = ref(false);  //是否已经验证了手机号进入重置密码阶段
const mChangePasswordButton = ref(true);  //修改密码按钮禁用状态
function handlePhoneValidation(isValid: boolean) {
    mCheckCode.value = isValid
}

// 点亮下一步按钮
watchEffect(() => {
    mNextStep.value = !mCheckCode.value;
});

//点亮重置密码按钮
watchEffect(() => {
    const pwd = mChangePasswordParams.password;
    const confirmPwd = mChangePasswordParams.confirm_password;
    // 密码长度校验
    const validLength = pwd.length >= 6 && pwd.length <= 16;
    // 密码一致性校验
    const isSame = pwd === confirmPwd && pwd !== '';
    // 只包含数字、字母、特殊字符
    const validChar = /^[A-Za-z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+$/.test(pwd);

    if (validLength && isSame && validChar) {
        mChangePasswordButton.value = false;
    } else {
        mChangePasswordButton.value = true;
    }
});

//校验修改手机验证码
const clkCheckCode = async () => {
    const { code } = await request.post<any>(API.checkChangePassWordCode, { sms_code: mPhoneLoginParams.sms_code });
    try {
        if (code === 0) {
            mChangePassword.value = true;
        }
    } catch (error) {
        console.log(error);
    }
};

//修改密码
const mRouter = useRouter();  //路由
const clkChangePassword = async () => {
    const { status } = await requestToast(mChangePasswordParams, API.changePassword, "修改成功")
    if (status) {
        //如果是客户端就关闭当前webview
        if (getUrlParamValue('access_token', mSomeField.clientfields) != null) {
            //通知客户端退出
            notifyClientLogout(mUser.token.user_name);
        } else { //如果不是客户端修改成功就去登陆
            mSomeField.$reset();    // 清空本地存储的一些字段
            mUser.$reset();   // 清空本地用户信息
            mRouter.push({
                path: '/login',
            });
        }
    }
};

function notifyClientLogout(userName: string) {
    // 通知客户端退出账号
    const logoutData = { user_name: userName };
    // 通知父窗口
    window.parent?.postMessage({ type: "LogOutAccount", data: logoutData }, "*");
    window.parent?.postMessage({ type: "ClosedCustomKf" }, "*");

    // 安卓
    (window as any).AndroidCallBack?.LogOutAccount(JSON.stringify(logoutData));
    window.AndroidCallBack?.ClosedCustomKf();

    // iOS
    (window as any).webkit?.messageHandlers?.LogOutAccount?.postMessage(logoutData);
    window.webkit?.messageHandlers?.ClosedCustomKf?.postMessage('close');
}

const { pageRef } = useFullPage()
</script>

<template>
    <div class="gr-bg" ref="pageRef">
        <cNavbar class="m-t-[5px]" iBgColor="#F6F6F6" :iFontColor="mStyles?.color2" leftArrow iTitle="重置密码"></cNavbar>
        <div class="gr-login">
            <div>
                <div>
                    <h1 class="text-[48px] font-bold m-b-[10px]" v-if="mChangePassword == false">
                        手机验证码验证
                    </h1>
                    <h1 class="text-[40px] m-b-[10px] font-normal" v-if="mChangePassword">
                        账号：{{ mUser.token.user_name }}
                    </h1>
                    <h2 class="text-[23px] font-350 color-[#3D3D3D]/60"
                        v-show="mBingPhone != '' && mChangePassword == false">
                        请验证您绑定的手机号{{ mBingPhone }}
                    </h2>
                </div>
                <div class="gr-change-password-code" v-if="mChangePassword == false">
                    <PhoneLogin class="m-t-[55px]" v-model="mPhoneLoginParams"
                        :api-config="{ sendCodeApi: API.changePassWordCode, type: 'changepasswrod' }"
                        @validation-change="handlePhoneValidation">
                    </PhoneLogin>
                    <cButton text="下一步" iLinearGradien :iColor="mStyles?.color10" class="w-[100%] mt-[35px]" round
                        iHeight="6vmin" iPadding="6vmin" :disabled="mNextStep" @click="clkCheckCode">
                    </cButton>
                </div>
                <div class="gr-change-password m-t-[55px]" v-if="mChangePassword">
                    <PasswordField v-model="mChangePasswordParams.password" label="新密码" placeholder="请输入新密码"></PasswordField>
                    <PasswordField v-model="mChangePasswordParams.confirm_password" placeholder="请再次输入新密码"
                        class="m-t-[35px]" label="新密码"></PasswordField>
                    <cButton text="重置密码" iLinearGradien :iColor="mStyles?.color10" class="w-[100%] mt-[35px]" round
                        iHeight="6vmin" iPadding="6vmin" :disabled="mChangePasswordButton" @click="clkChangePassword">
                    </cButton>
                    <div class="m-t-[30px] text-[23px] color-[#3D3D3D]/80">
                        <h1 class="text-[23px] m-b-[5px] font-normal">温馨提示：</h1>
                        <p class="m-b-[5px] font-normal">1. 密码长度为6-16位，只能包含数字、字母、特殊字符。</p>
                        <p class="m-b-[5px] font-normal">2.重置密码后将自动退出游戏</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.gr-bg {
    background: #F6F6F6;

    .gr-login {
        width: 590px;
        margin: 15px auto;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        min-height: calc(100vh - 16.146vh - 6.641vh);

        :deep(.van-field) {
            font-size: 32px;
            font-weight: 500;
            border-bottom: 1px solid rgba(61, 61, 61, 0.10);
            padding-left: 0;
            background: #F6F6F6;
        }

        .gr-label {
            display: flex;
            align-items: center;

            .gr-line {
                width: 2px;
                height: 32px;
                background: #3D3D3D1A;
                display: block;
                margin-left: 25px;
            }
        }
    }

    .van-hairline--top-bottom:after {
        display: none;
    }
}

.van-hairline--top-bottom:after {
    display: none;
}
</style>